// Cookies.set('mywebsite', user)
// Cookies.remove('mywebsite')
// Cookies.getJSON('mywebsite')
import Cookies from 'js-cookie'
import axios from 'axios'
const AUTH_SUCCESS = 'AUTH_SUCCESS'
const LOAD_DATA = 'LOAD_DATA'
const LOGOUT = 'LOGOUT'
const UPDATE_DATA = 'UPDATE_DATA'


const initState = {
  data:'',
  user: '', //用户名
  type: '' //用户类型
}

export default (state = initState, action) => {
  switch(action.type) {
    case AUTH_SUCCESS:
      return {...state,...action.payload}
    case LOAD_DATA:
      return {...state, ...action.payload}
    case LOGOUT :
      return {...initState}
    case UPDATE_DATA:
      return {...state,...action.payload}
    default :
      return state
  }
}

function authSuccess(obj) {
  const { pwd,...data } = obj
  return { type:AUTH_SUCCESS, payload:data }
}

export function updateData(data){
  return { type:UPDATE_DATA,payload:data }
}
export function loadData(userinfo) {
  return { type:LOAD_DATA,payload:userinfo }
}
export function logoutSubmit() {
  return { type:LOGOUT }
}

export function update(data) {
  return async dispatch => {
    const res = await axios.post('/user/update',data)
    if(res.status === 200 && res.data.code === 200) {
      dispatch(authSuccess(res.data))
    } else {
     
    }
  }
}

export function login({user,pwd}){
  if(!user || !pwd) {
    console.log('用户密码必须输入')
  }
  return async dispatch => {
    const res = await axios.post('/user/login',{user,pwd})
    if(res.status === 200 && res.data.code === 200) {
      dispatch(authSuccess(res.data))
    } else {
      
    }
  }
}

export function register({user,pwd,repeatpwd,type}){
  if(!user || !pwd) {
    console.log('用户名密码必须输入')
  }
  if (pwd !== repeatpwd) {
    console.log('密码和确认密码不相同')
  }
  return async dispatch => {
    const res = await axios.post('/user/register', {user,pwd})
    if (res.status === 200 && res.data.code === 200) {
      dispatch(authSuccess(res.data))
    } else {
      
    }
  }
}

export function dotest(){
  return async dispatch => {
    const res = await axios.get('/dotest')
    if (res.data.code === 200) {
      dispatch(updateData({data:res.data.data}))
    } else {
      
    }
  }
}
